/* eslint-disable compat/compat */
import axios from "axios";
import Cookie from "js-cookie";
import { notification } from 'antd';
import HttpError from "./error";
import showError from "../lib/utils/show-err";

export function getQueryString(params) {
  return Object.keys(params)
    .filter(k => params[k] !== undefined)
    .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`)
    .join("&");
}
const axiosInstance = axios.create();
axiosInstance.interceptors.response.use(
  response => {
    if (response.data.success) {
      return response.data;
    } else {
      const error = new HttpError(response.data.code, response.data.message);
      return Promise.reject(error);
    }
  },
  error => {
    const errorResponse = error.response;
    if(!errorResponse){
      error = new HttpError(
        500,
        '接口错误'
      );
      notification.error({
        message: '接口错误',
      });
      return Promise.reject(error);
    }
    if (errorResponse.status === 401) {
      Cookie.set("token", "");
      if(window.count <= 1){
        showError();
        window.count++;
      }      
      // window.location.reload();
    }
    if (errorResponse.data) {
      error = new HttpError(
        errorResponse.data.status,
        errorResponse.data.message || errorResponse.data.error
      );
    }
    return Promise.reject(error);
  }
);

function request(api, options) {
  api = api.replace("/node", "");
  return axiosInstance({
    ...options,
    url: `${window.host}${api}`,
  });
}

function get(api, options) {
  const config = {
    ...options,
    method: "get",
  };
  return request(api, config);
}

function post(api, options) {
  const config = {
    ...options,
    method: "post",
  };
  return request(api, config);
}

export default request;
export { get, post };
